﻿<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>canvas下雨</title>
<script src="../js/jquery.min.js"></script>
<style>
body {
	margin:0;
	padding:0;
}
canvas {
	display:block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>

<script>
 $(function() {
     var canvas = document.getElementById('canvas');
     var PI = Math.PI;
     var total = 8;
     canvas.width = window.innerWidth;
     canvas.height = window.innerHeight;
     var ctx = canvas.getContext('2d');


     ctx.strokeStyle = 'rgba(50,96,139,.8)';
     ctx.lineWidth = 2;
     //雨滴
     var arr = [];
     setInterval(function() {
         var x = Math.random() * (canvas.width - 14) + 14;
         var y = 0;
         var x2 = x - 15;
         var y2 = 30;
         arr.push({
             x: x,
             y: y,
             x2: x2,
             y2: y2
         })
     }, 25)

     function yudi() {
         ctx.clearRect(0, 0, canvas.width, canvas.height);
         var myGradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
         myGradient.addColorStop(0, 'rgba(9,13,38,.95)');
         myGradient.addColorStop(1, "rgba(33,18,6,.9)");
         ctx.fillStyle = myGradient;
         ctx.fillRect(0, 0, canvas.width, canvas.height);
         $.each(arr, function(i, m) {
             if (m) {
                 ctx.beginPath();
                 ctx.moveTo(m.x, m.y);
                 ctx.lineTo(m.x2, m.y2);
                 ctx.stroke();
                 m.x -= 5;
                 m.y += 10;
                 m.x2 = m.x - 15;
                 m.y2 = m.y + 30;
                 if (m.y2 > canvas.height) {
                     ctx.beginPath();
                     ctx.fillStyle = 'rgba(50,96,139,1)';
                     for (var j = 0; j < total; j++) {
                         var p = Math.random() * (m.x2 + 40 - (m.x2 - 40) + 1) + (m.x2 - 40); //水平扩散
                         var f = Math.random() * (canvas.height - (canvas.height - 40) + 1) + (canvas.height - 50) //垂直扩散
                         var ground = Math.random() * 3;
                         ctx.beginPath();
                         ctx.arc(p, f, ground, 0, 2 * PI);
                         ctx.fill();
                     }


                     arr.splice(i, 1);
                 }
             }
         });
         // ctx.save();

         window.requestAnimationFrame(yudi);
     }
     window.requestAnimationFrame(yudi);
 })
</script>

</body>
</html>
